var Resource = function () {

    var basePath = ROOT_PATH + 'upms/resource/',
        pagePath = ROOT_PATH + 'pages/upms/resource/',
        currNode = null,//当前选中的节点
        zTree = null,
        $form = $("#resourceForm");

    function initTree(treeId) {
        treeId = treeId;
        /**
         * 移除鼠标覆盖时的菜单
         */
        var removeHoverDom = function (treeId, treeNode) {
            $("#addNodeBtn_" + treeNode.tId).unbind().remove();
            $("#modifyBtn_" + treeNode.tId).unbind().remove();
            $("#upBtn_" + treeNode.tId).unbind().remove();
            $("#downBtn_" + treeNode.tId).unbind().remove();
            $("#modifyStatusBtn" +treeNode.tId).unbind().remove();
        };

        /**
         * 添加鼠标覆盖时的菜单
         */
        var addHoverDom = function (treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");

            // 添加修改子节点按钮
            if (treeNode.editNameFlag || $("#modifyBtn_" + treeNode.tId).length > 0) {
                return;
            }

            //根节点不能被修改。
            if (treeNode.level != 0) {
                var addNodeStr = "<span class='button edit' id='modifyBtn_" + treeNode.tId + "' title='修改' onfocus='this.blur();'></span>";
                sObj.after(addNodeStr);
                var modifyBtn_ = $("#modifyBtn_" + treeNode.tId);
                if (modifyBtn_) {
                    modifyBtn_.bind("click", function () {
                        modify(treeId, treeNode);
                        return false;
                    });
                }
            }


            // 添加增加子节点按钮
            if (treeNode.editNameFlag || $("#addNodeBtn_" + treeNode.tId).length > 0) {
                return;
            }

            var addNodeStr = "<span class='button add' id='addNodeBtn_" + treeNode.tId + "' title='添加服务资源' onfocus='this.blur();'></span>";
            sObj.after(addNodeStr);
            var addNodeBtn = $("#addNodeBtn_" + treeNode.tId);
            if (addNodeBtn) {
                addNodeBtn.bind("click", function () {
                    create(treeId, treeNode);
                    return false;
                });
            }

            // 添加禁用/启用子节点按钮
            if (treeNode.editNameFlag || $("#modifyStatusBtn" + treeNode.tId).length > 0) {
                return;
            }
            //根节点不能被禁用/启用
            if (treeNode.level != 0) {
                if (treeNode.status && treeNode.status.code == 1) {
                    var addNodeStr = "<span class='button ico_lock' id='modifyStatusBtn" + treeNode.tId + "' title='禁用' onfocus='this.blur();'></span>";
                    sObj.after(addNodeStr);
                    $("#"+treeNode.tId +"_a").attr("style",'color:#333;font-weight:normal;');

                } else if (treeNode.status && treeNode.status.code == 2) {
                    var addNodeStr = "<span class='button ico_nolock' id='modifyStatusBtn" + treeNode.tId + "' title='启用' onfocus='this.blur();'></span>";
                    sObj.after(addNodeStr);
                    $("#"+treeNode.tId +"_a").attr("style",'color:#999;font-weight:normal;');
                }
                var modifyStatusBtn = $("#modifyStatusBtn" + treeNode.tId);
                if (modifyStatusBtn) {
                    modifyStatusBtn.bind("click", function () {
                        modifyStatus(treeId, treeNode);
                        return false;
                    });
                }
            }

            return;
        };



        /**
         * 删除之前。
         */
        var beforeRemove = function (treeId, treeNode) {
            Dialog.confirm("确认删除？", function () {
                remove(treeId, treeNode);
            });
            return false;
        };

        /**
         * 点击事件之前
         */
        var beforeClick = function (treeId, treeNode) {
            if (treeNode.level != 0) {
                modify(treeId, treeNode);
            }
        };

        var setting = {
            treeId: treeId,
            async: {
                url: basePath + "list"
            },
            view: {
                // 用于当鼠标移动到节点上时，显示用户自定义控件
                addHoverDom: addHoverDom,
                // 用于当鼠标移动到节点上时，隐藏用户自定义控件
                removeHoverDom: removeHoverDom
            },
            check: {
                enable: false
            },
            edit: {
                enable: true,
                removeTitle: "删除",
                showRemoveBtn: function (treeId, treeNode) {
                    return treeNode.level != 0;
                }
            },
            callback: {
                beforeRemove: beforeRemove,
                beforeClick: beforeClick
            }
        };
        zTree = Tree.getTree4Admin(setting);
    }

    function showDetail(id) {
        get(id, function (result) {
            FormUtils.setValues($form, result);
        })
    }

    /**
     * 添加按钮的修改事件
     * @param id
     * @param treeNode
     */
    function modify(treeId, treeNode) {
        currNode = treeNode;
        FormUtils.clearForm($form);
        FormUtils.enableForm($form);
        showDetail(treeNode.id);
        $form.find('input[name="name"]').focus();
        //判断是否是菜单
        setTimeout(function(){
            var v=$('input[name="type"]:checked').val()
            if(v=='1'){
                $("#inputIcon").show();
            }
        },500);

    }
    /**
     * 添加按钮的启动/禁用事件
     * @param id
     * @param treeNode
     */
    function modifyStatus(treeId, treeNode){
        currNode = treeNode;
        var status;
        var result = [];
        //result = getChildren(result,treeNode);
        //alert(result);
        if (currNode.status && currNode.status.code == 1){
            status = 2;
            currNode.status.code = 2;
            //result = getChildren(result,treeNode,status);
            $("#modifyStatusBtn" + treeNode.tId).attr("class",'fa fa-unlock-alt');
            //for (var i = 0; i <result.length;i++){
            //    $("#modifyStatusBtn" + result[i]).attr("class",'button ico_nolock');
            //}

        }else {
            status = 1;
            currNode.status.code = 1;
            $("#modifyStatusBtn" + treeNode.tId).attr("class",'fa fa-unlock');
        }
        result = getChildren(result,treeNode,currNode.status);
        if(status==2){
            for (var i = 0; i <result.length;i++){
                $("#"+result[i] +"_a").attr("style",'color:#999;font-weight:normal;');
            }
        }else {
            for (var i = 0; i <result.length;i++){
                $("#"+result[i] +"_a").attr("style",'color:#333;font-weight:normal;');
            }
        }

        $.Ajax({
            url: basePath + "editStatus",
            method:"post",
            data: {id:treeNode.id,status:status},
            success: function () {
                Dialog.success("操作成功");
                refreshNode(treeId);
            }
        });
    }

    /**
     * 刷新当前节点
     */
    function refreshNode(treeId) {
        /*根据 treeId 获取 zTree 对象*/
        var zTree = $.fn.zTree.getZTreeObj(treeId),
            type = "refresh",
            silent = false,
            /*获取 zTree 当前被选中的节点数据集合*/
            nodes = zTree.getSelectedNodes();
        /*强行异步加载父节点的子节点。[setting.async.enable = true 时有效]*/
        zTree.reAsyncChildNodes(nodes[0], type, silent);
    }

    /**
     * 获取所有的子节点并修改状态
     * @param ids
     * @param treeNode
     * @param status
     * @returns {*}
     */
    function getChildren(ids,treeNode,status){
        //自己节点
        ids.push(treeNode.id);
        if (treeNode.isParent){
            for(var obj in treeNode.children){
                treeNode.children[obj].status = status;
                getChildren(ids,treeNode.children[obj],status);
            }
        }
        return ids;
    }


    /**
     * 添加按钮事件
     * @param id
     * @param treeNode
     */
    function create(treeId, treeNode) {
        currNode = treeNode;
        FormUtils.enableForm($form);
        FormUtils.clearForm($form);
        $form.find('input[name="pid"]').val(currNode.id);
        $form.find('input[name="name"]').focus();
    }

    /**
     * 添加删除事件
     * @param treeId
     * @param treeNode
     */
    function remove(treeId, treeNode) {
        $.Post(basePath + "delete", {id: treeNode.id}, function (data) {
            FormUtils.clearForm($form);
            Dialog.success("删除成功");
            zTree.removeNode(treeNode);
        })
    }


    /**
     * 给表单加上验证
     * @param formId
     */
    function initFormValidation(formId) {
        $form = $(formId);
        FormUtils.validate($form, {
            rules: {
                name: {
                    maxlength: 20,
                    required: true
                },
                funcs: {
                    maxlength: 500
                },
                seq: {
                    digits: true,
                    max: 65535
                },
                icon: {
                    maxlength: 100
                },
                type: {
                    required: true
                },
                class: {
                    maxlength: 50,
                },
                remark: {
                    maxlength: 100
                },
                url:{
                    required: true
                }
            },
            messages: {
                name: {
                    required: "资源名称不可为空",
                    maxlength: "最多允许输入20个字符"
                },
                type: {
                    required: "资源类型不可为空"
                },
                remark: {
                    maxlength: "最多允许输入100个字符"
                },
                icon: {
                    maxlength: "最多允许输入100个字符"
                },
                class: {
                    maxlength: "最多允许输入50个字符",
                },
                url:{
                    required: "URL不可为空",
                }
            },
            submitHandler: function (form) {
                var data = FormUtils.getFormObj(form);
                var url = $(form).attr("action");
                if (data.id) {
                    url += "/edit";
                } else {
                    url += "/create";
                }
                $.Ajax({
                    url: url,
                    data: data,
                    container: form,
                    success: function (result) {
                        if (data.id) {
                            //修改节点，修改后更新节点信息。
                            var newNode = zTree.transformTozTreeNodes(data)[0];
                            $.extend(currNode, newNode);
                            zTree.updateNode(currNode);
                        } else {
                            //新增节点，新增成功后添加节点。新节点需要从服务端获取该将诶点的id
                            var newNode = zTree.transformTozTreeNodes(result)[0];
                            zTree.addNodes(currNode, newNode.data);
                            zTree.expandNode(currNode, true, true, true);
                        }
                        Dialog.success("操作成功");
                        currNode = null;
                        FormUtils.clearForm($form);
                        FormUtils.disableForm($form);
                    }
                });
                return false;
            }
        });
        FormUtils.disableForm($form);
    }

    /**
     * 获取详情
     * @param id 资源id
     * @param fun　回调函数
     */
    var get = function (id, fun) {
        var url = basePath + 'get';
        var data = {
            id: id
        }
        $.Get(url, data, function (result) {
            if (result.success) {
                if ($.isFunction(fun)) {
                    fun(result.data);
                }
            }
        });
    }

    /**
     * 初始化图标选择
     */
    function initFontBox() {
        $.Get("pages/fontawesome.html",function (page) {
            var $dialog = $(page);
            $dialog.modal().on("shown.bs.modal", function (e) {
                //禁制跳转
                $(e.target).find("a").on("click",function () {
                    $(this).attr("href","javascript:;");
                    var clazz = $(this).children().attr("class");
                    $(this).parents("body").find("input[name='icon']").val(clazz);
                    $dialog.modal('hide');
                });
            })
        })
    }

    /**
     * 菜单缓存刷新
     */
    function refresh() {
        $.Get(basePath + "clearMenuCacheByUsrId",function (data) {
            Dialog.success(data.data);
        })
    }

    return {
        initTree: initTree,
        initFormValidation: initFormValidation,
        initFontBox:initFontBox,
        refresh:refresh
    }
}();